package cn.hchaojie.blog.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hchaojie.blog.domain.AjaxResponse;
import cn.hchaojie.blog.domain.Post;
import cn.hchaojie.blog.service.PostService;
import cn.hchaojie.blog.utils.ServiceProxyUtils;

@WebServlet(urlPatterns = {
		"/post/findAll",
		"/post/findPage",
		"/post/search",
		"/post/deleteBatch"
})
public class PostServlet extends BaseServlet {
	PostService service = (PostService) ServiceProxyUtils.createProxy(new PostService());
	
	protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 取到分页参数（page:第几页，limit，每页多少条），查询对应页的数据
		
		List<Post> all = service.findAll();
		
		writeListData(resp, all);
	}

	protected void findPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 取到分页参数（page:第几页，limit，每页多少条），查询对应页的数据
		int page = Integer.valueOf(req.getParameter("page"));
		int size = Integer.valueOf(req.getParameter("limit"));

		AjaxResponse<Post> data = service.findPage(page, size);
		data.setCode(0);
		data.setMsg("success");
		
		writePageData(resp, data);
	}
	
	protected void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 取到分页参数（page:第几页，limit，每页多少条），查询对应页的数据
		int page = Integer.valueOf(req.getParameter("page"));
		int size = Integer.valueOf(req.getParameter("limit"));
		String title = req.getParameter("title");
		String created = req.getParameter("created");
		String cidString = req.getParameter("category");
		Integer cid = (cidString == null || cidString.length() == 0 )
				? null 
				: Integer.valueOf(cidString);

		AjaxResponse<Post> data = service.searchPage(title, cid, created, page, size);
		data.setCode(0);
		data.setMsg("success");
		
		writePageData(resp, data);
	}
	
	public void deleteBatch(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// String string = req.getParameter("ids");
		// getParameter和getParameterMap
		String[] ids = req.getParameterMap().get("ids");
		
		service.deleteBatch(ids);
	}
}
